/*
 * PANEImageElement.cpp
 *
 *  Created on: Apr 27, 2009
 *      Author: wrice
 */
#include "PANEImp.h"
namespace PANEImp {

string PANEImageElement::TagName = "IMAGE";
string PANEImageElement::AttrNameSrc = "SRC";

PANEImageElement::PANEImageElement(PANEDocument * doc)
: PANEElement(TagName, doc)
, cvImg_(NULL)
, loadedURL_("")
{
}

PANEImageElement::~PANEImageElement() {
	if( getIsLoaded() ) cvReleaseImage( &cvImg_ );
}

DOMString PANEImageElement::getSrc() {
	return getAttribute( AttrNameSrc );
}

void PANEImageElement::setSrc(DOMString src) {
	setAttribute( AttrNameSrc, src );
}

unsigned long PANEImageElement::getWidth() {
	if( hasDesiredWidth() ) return PANEElement::getWidth();
	return getActualWidth(0);
}
unsigned long PANEImageElement::getHeight() {
	if( hasDesiredHeight() ) return PANEElement::getHeight();
	return getActualHeight(0);
}

unsigned long PANEImageElement::getActualWidth( unsigned long availableWidth ) {
	if( false == getIsLoaded() ) loadURL();
	if(NULL == cvImg_) ;
	return cvImg_->width;
}

unsigned long PANEImageElement::getActualHeight( unsigned long availableWidth ) {
	if( false == getIsLoaded() ) loadURL();
	if(NULL == cvImg_) return 0;
	return cvImg_->height;
}

void PANEImageElement::render( IplImage * img ) {
	if( false == isRepaintRequested() ) return;
	if( false == getVisible() ) return;
	if( false == getIsLoaded() ) loadURL();
	if( false == getIsLoaded() ) return;

	const int maxWidth = img->width;
	const int maxHeight = img->height;
	const long leftOffset = getLeftOffset();
	const long topOffset = getTopOffset();

	for( int i = 0; i < cvImg_->height && i + topOffset < maxHeight; ++i )
		for( int j = 0; j < cvImg_->width && j + leftOffset < maxWidth; ++j ) {
			const CvScalar aDot = cvGet2D( cvImg_, i, j );
			cvSet2D( img, topOffset + i, leftOffset + j, aDot );
		}

	repainted();
}

DOMString PANEImageElement::getImageURL() {
	return getAttribute( AttrNameSrc );
}

bool PANEImageElement::getIsLoaded() {
	return getSrc() == loadedURL_ && cvImg_;
}

void PANEImageElement::loadURL() {
	if( cvImg_ ) cvReleaseImage( &cvImg_ );

	const string filename = getAttribute( AttrNameSrc );
	if( filename.empty() ) return;

	cvImg_ = cvLoadImage( filename.c_str() );
	loadedURL_ = filename;
	requestRepaint();
}

}
